package controllers

import (
	"ai/ai_control/utils/log"
	"newAi/new_web/models"
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/tealeg/xlsx"
)

type CdrController struct {
	BaseController
}

var CdrConfigArr = [...]string{
	"普通肯定", "普通否定", "客户反感", "潜在客户", "未知", "短信", "挽留","判断"}

func (self *CdrController) CdrList() {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println("failed:", err)
		}
	}()
	self.Data["pageTitle"] = "通话详单"
	task, _ := models.TaskIdName()
	taskArr := make([]models.AiTask, len(task))
	for _, v := range task {
		taskModel := models.AiTask{}
		taskModel.Id = v.Id
		taskModel.Tk_name = v.Tk_name
		taskArr = append(taskArr, taskModel)
	}
	myTime := time.Now()
	fmt.Println(myTime.Format("2006_01_02"))
	user, conut, conncet, err := models.SearchCdrInfo(myTime.Format("2006_01_02"), self.userId)
	if err != nil {
		logger.Error("查询当天的出错了")
	}
	self.Data["user"] = user
	self.Data["phone"] = conut
	self.Data["link"] = conncet
	self.display()
}
func (self *CdrController) ContentList() {
	self.Data["call_id"] = self.GetString("call_id")
	self.Data["audio"] = self.GetString("audio")
	self.Data["pageTitle"] = "对话记录"
	self.display()
}

func (self *CdrController) CdrTable() {

	//列表
	page, err := self.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := self.GetInt("limit")
	if err != nil {
		limit = 5
	}
	var conut int64
	var cdr = make([]models.AiCdr, 0)
	if self.GetString("startDate") == "" {
		myTime := time.Now()
		fmt.Println(myTime.Format("2006_01_02"))
		cdr, conut, err = models.SearchCdr1(myTime.Format("2006_01_02"), self.userId,page, limit)
	} else {
		start := self.FormatTimes(self.GetString("startDate"))
		end := self.FormatTimes(self.GetString("endDate"))
		taskid, _ := self.GetInt64("taskId")
		phone := self.GetString("phone")
		uuid := self.GetString("uuid")
		intention, _ := self.GetInt("intention")
		timemax := self.GetString("timemax")
		timemin := self.GetString("timemin")
		classify := self.GetString("classify")
		cdr, conut, err = models.SearchCdr(taskid, start, end, phone, timemax, timemin, classify, uuid, intention, page, limit, self.userId)
	}
	if err != nil {
		self.ErrorLog(err)
		return
	}

	//self.pageSize = limit
	//group 列表
	//gw, err := models.GatewayIdName()//网关暂时不需要
	//self.CheckError(err)
	user_group, err := models.UserGroupIdName()
	self.CheckError(err)
	task, err := models.TaskIdName()
	//查询条件
	//filters := make([]interface{}, 0)
	//if self.isOrg == true {
	//	filters = append(filters, "account_id", self.userId)
	//}
	//result, count := models.AiCdrGetList(page, self.pageSize, filters...)
	list := make([]map[string]interface{}, len(cdr))
	for k, v := range cdr {
		row := make(map[string]interface{})
		row["id"] = v.Id
		row["call_id"] = v.Call_id
		for _, b := range user_group {
			if v.Account_id == b.Id {
				row["account_id"] = b.LoginName
				break
			}
		}
		row["caller"] = v.Caller
		if v.Caller == "" {
			row["caller"] = v.Callee
		}
		row["callee"] = v.Callee
		row["start_time"] = self.FormatTime(v.Start_time)
		row["end_time"] = self.FormatTime(v.End_time)
		if v.Duration == 0 {
			row["duration"] = "未接通"
		} else {
			row["duration"] = v.Duration
		}
		row["fee_rate"] = v.Fee_rate
		row["bill_balance"] = v.Bill_balance
		//for _, c := range gw {
		//	if v.Route_id == c.Id {
		//		row["route_id"] = c.Gateway_name
		//	}
		//}
		for _, e := range task {
			if v.Task_id == e.Id {
				row["task_id"] = e.Tk_name
				break
			}
		}
		row["record_base"] = v.Record_base
		row["classify"] = getClassify(v.Talk_crycle)
		row["record_path"] = v.Record_path
		row["intention"] = CdrConfigArr[v.Intention]
		row["term_status"] = v.Term_status
		row["term_cause"] = v.Term_cause
		row["hangup_dispostion"] = v.Hangup_dispostion
		list[k] = row
	}
	self.ajaxList("成功", MSG_OK, conut, list)
}
//获取几类客户
func getClassify(talk_crycle string) string {
	i,_:=strconv.Atoi(talk_crycle)
	if  i >= 3 {
		return "A类客户"
	}else if i >=2 {
		return "B类客户"
	}else if i >=1 {
		return "C类客户"
	}else {
		return "D类客户"
	}
}

func (self *CdrController) ContentTable() {
	//列表
	call_id := self.GetString("call_id")
	fmt.Println("--------call id -------->", call_id)
	page, err := self.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := self.GetInt("limit")
	if err != nil {
		limit = 30
	}

	self.pageSize = limit

	//查询条件
	filters := make([]interface{}, 0)
	filters = append(filters, "call_id", call_id)
	result, count := models.AiFlowContentGetList(page, self.pageSize, filters...)
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["id"] = v.Id
		row["call_id"] = v.Call_id
		row["ai_speak"] = v.Ai_speak
		row["people_speak"] = v.People_speak
		row["node_name"] = v.Node_name
		row["flow_time"] = self.FormatTime(v.Flow_time)
		row["match_key"] = v.Match_key
		row["process_id"] = v.Process_id
		row["desc"] = models.AiFlowContentToProcessDesc(v.Process_id)
		if len(v.Voice_path) > 0 {
			row["voice_path"] = Substr2(v.Voice_path, strings.LastIndex(v.Voice_path, "/")+1, len(v.Voice_path))
		} else {

			row["voice_path"] = " "
		}
		list[k] = row
	}
	self.ajaxList("成功", MSG_OK, count, list)
}

func (self *CdrController) ContentTableAllList() {
	//列表
	call_id := self.GetString("call_id")

	//查询条件
	filters := make([]interface{}, 0)
	filters = append(filters, "call_id", call_id)
	result, count := models.AiFlowContentGetListAll(filters...)
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["id"] = v.Id
		if strings.Contains(v.Ai_speak, ".wav") || strings.Contains(v.Ai_speak, ".mp3") {
			row["ai_speak"] = v.Description
		}else {
			row["ai_speak"] = v.Ai_speak
		}
		row["people_speak"] = v.People_speak
		row["flow_time"] = self.FormatTime(v.Flow_time)
		if len(v.Voice_path) > 0 {
			row["voice_path"] = Substr2(v.Voice_path, strings.LastIndex(v.Voice_path, "/")+1, len(v.Voice_path))
		} else {
			row["voice_path"] = " "
		}
		list[k] = row
	}
	self.ajaxList("成功", MSG_OK, count, list)
}

func (self *CdrController) ContentTableOne() {
	//列表
	call_id := self.GetString("call_id")

	bool,err:=models.IsRuntimeByCallId(call_id,self.userId)
	if err != nil {
		logger.Error(err)
	}
	if bool == false{
		self.ajaxMessage("删除数据", MSG_ERR, MSG_ERR)
		return
	}
	id, _ := self.GetInt64("id")
	//查询条件
	filters := make([]interface{}, 0)
	filters = append(filters, "call_id", call_id)
	filters = append(filters, "id__gt", id)
	result, count := models.AiFlowContentGetListAll(filters...)
	list := make([]map[string]interface{}, len(result))
	for k, v := range result {
		row := make(map[string]interface{})
		row["id"] = v.Id
		if strings.Contains(v.Ai_speak, ".wav") || strings.Contains(v.Ai_speak, ".mp3") {
			row["ai_speak"] = v.Description
		}else {
			row["ai_speak"] = v.Ai_speak
		}
		row["people_speak"] = v.People_speak
		row["flow_time"] = self.FormatTime(v.Flow_time)
		if len(v.Voice_path) > 0 {
			row["voice_path"] = Substr2(v.Voice_path, strings.LastIndex(v.Voice_path, "/")+1, len(v.Voice_path))
		} else {
			row["voice_path"] = " "
		}
		list[k] = row
	}
	self.ajaxList("成功", MSG_OK, count, list)
}

func (self *CdrController) SearchCdr() {
	cdrInfo := make(map[string]interface{}, 0)

	start := self.FormatTimes(self.GetString("startDate"))
	end := self.FormatTimes(self.GetString("endDate"))
	taskid, _ := self.GetInt64("taskId")
	phone := self.GetString("phone")
	intention, _ := self.GetInt("intention")
	timemax := self.GetString("timemax")
	timemin := self.GetString("timemin")
	classify := self.GetString("classify")
	uuid := self.GetString("uuid")
	user, count, connect, err := models.SearchCdrInfos(taskid, start, end, phone, timemax, timemin, classify, uuid, intention, self.userId)
	if err != nil {
		logger.Error("查询当天出问题")
	}
	cdrInfo["user"] = user
	cdrInfo["phone"] = count
	cdrInfo["link"] = connect

	self.ajaxMsg(cdrInfo, MSG_OK)
}

func Substr2(str string, start int, end int) string {
	rs := []rune(str)
	length := len(rs)

	if start < 0 || start > length {
		panic("start is wrong")
	}

	if end < 0 || end > length {
		panic("end is wrong")
	}

	return string(rs[start:end])
}

func (self *CdrController) ExportExsel() {
	file := xlsx.NewFile()
	sheet, _ := file.AddSheet("Sheet1")
	//表头部分
	row := sheet.AddRow()
	row.SetHeightCM(1) //设置每行的高度
	cell := row.AddCell()
	cell.Value = "Id"
	cell = row.AddCell()
	cell.Value = "呼叫标识"
	cell = row.AddCell()
	cell.Value = "主叫号码"
	cell = row.AddCell()
	cell.Value = "开始时间"
	cell = row.AddCell()
	cell.Value = "结束时间"
	cell = row.AddCell()
	cell.Value = "客户意向"
	cell = row.AddCell()
	cell.Value = "费率"
	cell = row.AddCell()
	cell.Value = "通话时长"
	cell = row.AddCell()
	cell.Value = "费用"
	cell = row.AddCell()
	cell.Value = "任务归属"
	cell = row.AddCell()
	cell.Value = "归属用户"
	cell = row.AddCell()
	cell.Value = "录音"
	err := file.Save("upload/file.xlsx")
	if err != nil {
		panic(err)
	}

	//获取搜索内容
	var cdr = make([]models.AiCdr, 0)
	start := self.GetString("startDate")
	end := self.GetString("endDate")
	taskid, _ := self.GetInt64("taskId")
	phone := self.GetString("phone")
	intention, _ := self.GetInt("intention")
	timemax := self.GetString("timemax")
	timemin := self.GetString("timemin")
	classify := self.GetString("classify")
	uuid := self.GetString("uuid")
	cdr, _, err = models.SearchCdr(taskid, start, end, phone, timemax, timemin , classify, uuid , intention, 0, 0, self.userId)
	if err != nil {
		self.ErrorLog(err)
		fmt.Println(err)
		return
	}
	fmt.Println("cdr", cdr)

	//获取网关
	user_group, err := models.UserGroupIdName()
	self.CheckError(err)
	task, err := models.TaskIdName()
	for _, v := range cdr {
		self.sevaExsel(v, user_group, task)
	}

	self.ajaxMsg("成功", MSG_OK)
}

func (self *CdrController) sevaExsel(cdrlist models.AiCdr, user_group []*models.Admin, task []*models.AiTask) {
	file, err := xlsx.OpenFile("upload/file.xlsx")
	if err != nil {
		panic(err)
	}
	first := file.Sheets[0]
	row := first.AddRow()
	row.SetHeightCM(1)
	cell := row.AddCell()
	cell.Value = strconv.FormatInt(cdrlist.Id, 10)
	cell = row.AddCell()
	cell.Value = cdrlist.Call_id
	cell = row.AddCell()
	cell.Value = cdrlist.Caller
	cell = row.AddCell()
	cell.Value = self.FormatTime(cdrlist.Start_time)
	cell = row.AddCell()
	cell.Value = self.FormatTime(cdrlist.End_time)
	cell = row.AddCell()
	cell.Value = CdrConfigArr[cdrlist.Intention]
	cell = row.AddCell()
	cell.Value = strconv.FormatFloat(float64(cdrlist.Fee_rate), 'E', -1, 32)
	cell = row.AddCell()
	if cdrlist.Duration == 0 {
		cell.Value = "未接通"
	} else {
		cell.Value = strconv.Itoa(cdrlist.Duration)
	}
	cell = row.AddCell()
	cell.Value = strconv.FormatFloat(float64(cdrlist.Bill_balance), 'E', -1, 32)
	cell = row.AddCell()
	for _, e := range task {
		if cdrlist.Task_id == e.Id {
			cell.Value = e.Tk_name
			break
		}
	}
	cell = row.AddCell()
	cell.Value = strconv.Itoa(cdrlist.Account_id)
	for _, b := range user_group {
		if cdrlist.Account_id == b.Id {
			cell.Value = b.LoginName
			break
		}
	}
	cell = row.AddCell()
	cell.Value = cdrlist.Record_path

	err = file.Save("upload/file.xlsx")
	if err != nil {
		panic(err)
	}
}
//processid获取tplid
func (self *CdrController) GetTplByProcessId() {

	id , _:= self.GetInt("id")
	fmt.Println(id)
	process, err := models.ProcessGetById(id)
	if err != nil {
		logger.Error("根据processid获取tplid失败")
	}

	self.ajaxJson(process, MSG_OK)
}
